package org.xzx.cloud.ad.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xzx.cloud.ad.constant.Constants;
import org.xzx.cloud.ad.dao.AdUserRepository;
import org.xzx.cloud.ad.entity.AdUser;
import org.xzx.cloud.ad.exception.AdException;
import org.xzx.cloud.ad.service.IAdUserService;
import org.xzx.cloud.ad.utils.CommonUtils;
import org.xzx.cloud.ad.vo.CreateUserRequest;
import org.xzx.cloud.ad.vo.CreateUserResponse;

/**
 * @author xzx
 */
@Slf4j
@Service
public class AdUserServiceImpl implements IAdUserService {

    private final AdUserRepository userRepository;

    public AdUserServiceImpl(AdUserRepository adUserRepository) {
        this.userRepository = adUserRepository;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CreateUserResponse createUser(CreateUserRequest request) throws AdException {
        if (!request.validate()) {
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        AdUser oldUser = userRepository.findByUsername(request.getUsername());
        if (oldUser != null) {
            throw new AdException(Constants.ErrorMsg.SAME_NAME_ERROR);
        }
        AdUser newUser = userRepository.save(new AdUser(request.getUsername(),
                CommonUtils.md5(request.getUsername())));
        return new CreateUserResponse(newUser.getId(), newUser.getUsername(), newUser.getToken(),
                newUser.getCreateTime(), newUser.getUpdateTime());
    }


    /**
     * TODO {@link Transactional} 注解：默认抛出运行时异常 {@link RuntimeException} 才回滚，通过 rollbackFor 属性指定抛出某种异常才回滚
     */
}
